#include "Parse.hpp"
#include "Usage.hpp"
#include "HttpServer.hpp"

#include <memory>
#include <fstream>

#define WEBROOT "./wwwroot"
#define HOMEPAGE "/index.html"

void ProcessRoutine(int serverSock) {
  char buff[10240];
  // 接收任务
  ssize_t ret = recv(serverSock, buff, sizeof(buff) - 1, 0);
  if(ret > 0) {
    buff[ret] = 0;
    std::cout << buff << std::endl << "----------------" << std::endl;
  }

  // 执行任务并回应
  std::vector<std::string> vs;
  Parse(buff, "\r\n", vs);

  std::vector<std::string> firstLine;
  Parse(vs[0], " ", firstLine);

  std::string path = WEBROOT;
  if(firstLine[1] == "/") {
    path += HOMEPAGE;
  } else {
    path += firstLine[1];
  }
  
  std::string content;
  std::ifstream ifile(path);
  if(ifile.is_open()) {
    std::string line;
    while(std::getline(ifile, line)) {
      content += line;
    }
    ifile.close();
  }

  std::string httpResponse;

  if(content == " ") {
    httpResponse = "HTTP/1.1 301 Move Permanently\r\n";
    httpResponse += "Location: ./404.html\r\n";
  } else {
		httpResponse = "HTTP/1.1 200 OK\r\n";
    httpResponse += "Content-Type: text/html\r\n";
    httpResponse += "Set-Cookie: 这是一个Cookie\r\n";
    httpResponse += "Content-Length: " + std::to_string(content.size()) + "\r\n";
	}

	// 报头不给
  // 空行
	httpResponse += "\r\n";
	httpResponse += content;
	
  send(serverSock, httpResponse.c_str(), httpResponse.size(), 0);	



}	

int main(int argc, char* argv[]) {
  if(argc != 2) {
    Usage(argv[0]);
    exit(1);
  }
  
  std::unique_ptr<HttpServer> httpserver(new HttpServer(atoi(argv[1]), ProcessRoutine));
  httpserver->Start();
  return 0;
}

